// 用户相关的api
const express = require("express");
const router = express.Router();
// 引入passport 检证token
const passport = require("passport");
// 引入Visit
const Visit = require("../models/Visit");
// 引入blog
const Blog = require("../models/Blog");

/* $route POST api/census/visit
 * @desc 返回json
 * @access private
 * 后台获取访问次数
 */
router.post(
	"/visit",
	passport.authenticate("jwt", { session: false }),
	(req, res) => {
		const limit = 15;
		const skip = 0;
		Visit.find()
			.limit(limit)
			.skip(skip)
			.sort({ id: -1 })
			.then((visit) => {
				if (!visit) {
					return res.status(404).json("暂无数据！");
				} else {
					res.json(visit);
				}
			});
	}
);

/* $route POST api/census/setvisit
 * @desc 返回json
 * @access public
 * 设置访问次数
 */
router.post("/setvisit", (req, res) => {
	const years_month = req.body.years_month;
	const number = 1;

	Visit.findOne({ years_month }).then((visit) => {
		if (visit) {
			let _id = visit.id;
			Visit.findByIdAndUpdate(
				{ _id },
				{ $inc: { number: 1 } },
				{ new: true }
			);
		} else {
			const visitdata = {
				years_month,
				number,
			};
			new Visit(visitdata).save();
		}
		res.json("成功");
	});
});

/* $route POST api/census/maximum
 * @desc 返回json
 * @access private
 * 后台获取访问最多的blog
 */
router.post(
	"/maximum",
	passport.authenticate("jwt", { session: false }),
	(req, res) => {
		const limit = 15;
		const skip = 0;
		Blog.find()
			.limit(limit)
			.skip(skip)
			.sort({ number: -1 })
			.then((maximum) => {
				if (!maximum) {
					return res.status(404).json("暂无数据！");
				} else {
					res.json(maximum);
				}
			});
	}
);

module.exports = router;
